package com.perye.dokit.utils;

import org.springframework.web.multipart.MultipartFile;

import java.io.File;

public class UploadFile {
    /**
     *
     * @param uploadFile
     * @param uploadFilePath 文件上传路径
     * @param uploadFileMapping，文件映射路径
     * @return
     */

    public static String uploadFile(MultipartFile uploadFile, String uploadFilePath, String uploadFileMapping) {
        //1、基本校验
        if (StringUtils.isBlank(uploadFile.getOriginalFilename()) || uploadFile == null ) {
            return null;
        }
        //2、配置文件路径+文件模块名称+UUID文件名
        StringBuffer uploadPath = new StringBuffer(uploadFilePath);
        uploadPath.append(File.separator);
        String suffix = FileUtil.getExtensionName(uploadFile.getOriginalFilename());
        uploadPath.append(UuidUtil.get32UUID() + "." + suffix);
        //3、文件上传
        File file = upload(uploadFile, uploadPath.toString());
        //4、返回映射路径
        String httpPath = null == file ? null : uploadPath.replace(0, uploadFilePath.length(), uploadFileMapping).toString();
        return httpPath.replace("\\", "/");
    }
    /**
     * 将文件名解析成文件的上传路径
     *
     * @param file  上传文件
     * @param filePath 上传文件目录名称
     * @return 执行结果

     */
    private static File upload(MultipartFile file, String filePath) {
        try {
            // getCanonicalFile 可解析正确各种路径
            File dest = new File(filePath).getCanonicalFile();
            // 检测是否存在目录
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            // 文件写入
            file.transferTo(dest);
            return dest;
        } catch (Exception e) {
        }
        return null;
    }
}
